from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.core.validators import EmailValidator
from rest_framework import serializers
from rest_framework.validators import UniqueValidator


class RegisterSerializer(serializers.ModelSerializer):  # 用于注册的序列化器类
    # 用户名必须唯一
    username = serializers.CharField(max_length=150, validators=[UniqueValidator(queryset=User.objects.all())])
    # 邮箱必须合法且唯一
    email = serializers.EmailField(validators=[EmailValidator(), UniqueValidator(queryset=User.objects.all())])

    class Meta:
        model = User
        fields = ('username', 'password', 'email')  # 注册时只需要提交这三个字段就好

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data.get('password'))
        return super().create(validated_data)
